#pragma once
#include<iostream>
#include<cstring>
#include<signal.h>
#include"TcpServer.hpp"
#include"Util.hpp"
#include"Log.hpp"
#include"Task.hpp"
#include"ThreadPool.hpp"

#define PORT 8080

class HttpServer
{
private:
    int port;
    bool stop;
public:
    HttpServer(int _port=PORT):port(_port),stop(false)
    {}
    void InitServer()
    {
        //SIGPIPE信号需要忽略
        //如果不忽略，写入错误时会导致server崩溃
        signal(SIGPIPE, SIG_IGN);
        //tcp_server = TcpServer::GetInstance(port);
    }
    void Loop()//执行循环，创建线程
    {
        TcpServer* tsvr = TcpServer::GetInstance(port);
        LOG(INFO, "loop ... begin");
        while(!stop)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            int sock = accept(tsvr->Sock(), (struct sockaddr*)&peer, &len);
            
            if(sock < 0){//申请失败，进行下一次等待申请
                continue;       
            }

            LOG(INFO, "Get a new link");
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }
    ~HttpServer(){}
};